package com.example.preparedstatement.crud;

import com.example.bean.Customer;
import com.example.util.JDBCUtils;
import org.junit.Test;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;

// 查询customers表
public class CustomerForQuery {

    @Test
    public void testQuery1() {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            // 获取连接
            connection = JDBCUtils.getConnection();

            // 编译SQL
            String sql = "SELECT id, name, email, birth FROM customers WHERE id = ?";
            preparedStatement = connection.prepareStatement(sql);
            // 设置参数
            preparedStatement.setInt(1, 2);

            // 查询结果
            resultSet = preparedStatement.executeQuery();
            // 遍历结果集
            if (resultSet.next()) {
                int id = resultSet.getInt(1);
                String name = resultSet.getString(2);
                String email = resultSet.getString(3);
                Date birth = resultSet.getDate(4);

                // 方式一：直接输出
                System.out.println("id=" + id + ", name=" + name + ", email=" + email + ", birth=" + birth);

                // 方式二：对象数组
                Object[] data = new Object[]{id, name, email, birth};

                // 方式三：ORM，将数据封装成对象（推荐）
                Customer customer = new Customer(id, name, email, birth);
                System.out.println(customer);
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        } finally {
            // 释放资源
            JDBCUtils.closeResource(connection, preparedStatement, resultSet);
        }
    }


    // 针对customers表的通用查询操作
    public Customer queryForCustomers(String sql, Object... args) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            // 获取连接
            connection = JDBCUtils.getConnection();

            // 编译SQL
            preparedStatement = connection.prepareStatement(sql);
            // 设置参数
            for (int i = 0; i < args.length; i++) {
                preparedStatement.setObject(i + 1, args[i]);
            }

            // 查询结果
            resultSet = preparedStatement.executeQuery();
            // 获取结果集元数据
            ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
            int columnCount = resultSetMetaData.getColumnCount();

            // 遍历结果集
            if (resultSet.next()) {
                Customer customer = new Customer();
                for (int i = 0; i < columnCount; i++) {
                    Object columnValue = resultSet.getObject(i + 1);
                    // 获取列名
                    String columnName = resultSetMetaData.getColumnLabel(i + 1);

                    // 通过反射设置属性值
                    Field field = customer.getClass().getDeclaredField(columnName);
                    field.setAccessible(true);
                    field.set(customer, columnValue);
                }
                return customer;
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        } finally {
            // 释放资源
            JDBCUtils.closeResource(connection, preparedStatement, resultSet);
        }
        return null;
    }

    @Test
    public void testQueryForCustomers() {
        String sql = "SELECT id, name, email, birth FROM customers WHERE id = ?";
        Customer customer = queryForCustomers(sql, 4);
        System.out.println(customer);

        String sql2 = "SELECT id, name, email, birth FROM customers WHERE name = ?";
        Customer customer2 = queryForCustomers(sql2, "root");
        System.out.println(customer2);
    }

}
